package com.guxingke.typecho4j.jfinal.model;

import java.util.List;

import com.jfinal.plugin.activerecord.Model;

/**
 * typecho_options表 对应的model
 * */
public class Meta extends Model<Meta> {
	private static final long serialVersionUID = 1330218674053390317L;
	public static final Meta dao = new Meta();

	public List<Meta> findAll() {
		return find("select * from typecho_metas");
	}

	public Long findMidByMSlug(String slug) {
		return findFirst(
				"select mid from typecho_metas where slug = ?",
				slug).getLong("mid");
	}

	public List<Meta> getTagsByContentId(Long contentId) {
		String sql = "select m.* from typecho_contents c left join typecho_relationships r on c.cid=r.cid left join typecho_metas m on m.mid = r.mid where c.cid = ? and m.type = ?";
		return find(sql, contentId, "tag");
	}

	public List<Meta> getCategoriesByContentId(Long contentId) {
		String sql = "select m.* from typecho_contents c left join typecho_relationships r on c.cid=r.cid left join typecho_metas m on m.mid = r.mid where c.cid = ? and m.type = ?";
		return find(sql, contentId, "category");
	}

	public List<Meta> getCategories() {
		return find("select * from typecho_metas where type = 'category' ");
	}

	public Long getCountByMetaSlug(String prop) {
		Meta meta = findFirst(
				"select count from typecho_metas where slug=?",
				prop);
		if (meta == null) {
			return 0L;
		}
		return meta.getLong("count");
	}

	public Long getCategoriesNum() {
		String sql = "select count(mid) as count from typecho_metas where type = 'category'  group by type";
		Meta result = findFirst(sql);
		if (result == null) {
			return 0L;
		}
		return result.getLong("count");
	}

	public void increaseCount(Long mid) {
		Meta result = findById(mid);
		result.set("count", result.getLong("count") + 1);
		result.update();
	}

	public List<Meta> getTags() {
		return find("select * from typecho_metas where type = 'tag' ");
	}

	public void deleteTagById(Long mid) {
		Relationships.dao.deleteByMid(mid);
		deleteById(mid);
	}

	public void mergetCategory(Long mid, Long merge) {
		Relationships.dao.mergeCategory(mid, merge);
	}
}
